import { Divider, Input, Button, Avatar, message } from "antd";
import { memo, useEffect, useState } from "react";
import type { Article, Comment as CommentType, User } from "@/types";
import { LikeOutlined } from "@ant-design/icons";
import { addComment, addLike, addReply, mockUsers } from "@/mock/data";
import PubSub from 'pubsub-js';

export const Comment = memo(({ comments, article }: { comments: CommentType[], article: Article }) => {
  // 评论内容
  const [commentValue, setCommentValue] = useState('');
  // 回复内容
  const [replyContent, setReplyContent] = useState('');
  // 评论列表
  const [commentList, setCommentList] = useState<CommentType[]>(comments);
  const [messageApi, contextHolder] = message.useMessage();
  // 更新评论数并发布
  const updateCommentCount = (comments: CommentType[]) => {
    const count = comments.reduce((acc, comment) => {
      return acc + (comment.replies?.length || 0) + 1;
    }, 0);
    // 发布评论数
    PubSub.publish('commentCount', count);
  };

  // 初始化评论列表,并监听评论列表的变化
  useEffect(() => {
    setCommentList(comments)
    updateCommentCount(comments);
  }, [comments])

  // 用户发表评论
  const handleComment = async () => {
    if (!commentValue.trim()) {
      messageApi.error('请输入评论内容');
      return;
    }
    if (!article) return;

    try {
      // 添加评论
      const newComment = await addComment({
        content: commentValue,
        author: mockUsers[0], // 默认第一个用户
        articleId: article.id
      })
      // 更新评论列表
      const updatedCommentList = [newComment, ...commentList];
      setCommentList(updatedCommentList);
      // 更新评论数
      updateCommentCount(updatedCommentList);
      // 清空评论输入框
      setCommentValue('');
      messageApi.success('评论成功');
    } catch (error) {
      console.error('评论失败:', error);
      messageApi.error('评论失败');
    }
  }

  // 用户回复评论
  const handleReply = async (commentId: string, replyTo: User) => {
    if (!replyContent.trim()) {
      messageApi.warning('请输入回复内容');
      return;
    }
    if (!article) return;

    try {
      const newReply = await addReply({
        content: replyContent,
        author: mockUsers[1],
        replyTo,
        articleId: article.id,
        parentId: commentId
      });

      // 查找目标评论的父评论ID（最顶层评论）
      const findTopLevelParentId = (comments: CommentType[], targetId: string): string | null => {
        for (const comment of comments) {
          if (comment.id === targetId) {
            return comment.id; // 这是主评论
          }
          if (comment.replies) {
            for (const reply of comment.replies) {
              if (reply.id === targetId) {
                return comment.id; // 找到父评论
              }
            }
          }
        }
        return null;
      };

      const topLevelParentId = findTopLevelParentId(commentList, commentId);

      if (topLevelParentId) {
        // 将新回复添加到最顶层父评论的replies数组中
        const updatedCommentList = commentList.map(comment => {
          if (comment.id === topLevelParentId) {
            return {
              ...comment,
              replies: [newReply, ...(comment.replies || [])]
            };
          }
          return comment;
        });
        setCommentList(updatedCommentList);
        // 更新评论数
        updateCommentCount(updatedCommentList);
      }

      setReplyContent('');
      setReplyTo(null);
      messageApi.success('回复成功');
    } catch (error) {
      console.error('回复失败:', error);
      messageApi.error('回复失败');
    }
  }

  // 用户点赞评论
  const handleLike = async (commentId: string) => {
    try {
      const newComment = await addLike(commentId)
      if (newComment) {
        // 递归更新评论列表，包括回复评论
        const updateCommentList = (comments: CommentType[]): CommentType[] => {
          return comments.map(comment => {
            // 如果是主评论
            if (comment.id === commentId) {
              return newComment;
            }
            // 如果是回复评论，递归查找并更新
            if (comment.replies && comment.replies.length > 0) {
              return {
                ...comment,
                replies: updateCommentList(comment.replies)
              };
            }
            return comment;
          });
        };

        const updatedCommentList = updateCommentList(commentList);
        setCommentList(updatedCommentList);
        messageApi.success('点赞成功');
      }
    } catch (error) {
      console.error('点赞失败:', error);
      messageApi.error('点赞失败');
    }
  }

  const [replyTo, setReplyTo] = useState<string | null>(null)

  // 渲染评论项
  const renderCommentItem = (item: CommentType, level: number = 0) => {
    const isReply = level > 0;
    const indentClass = isReply ? 'ml-8' : '';
    return (
      <div className={`bg-white rounded-lg p-4 mb-4 ${indentClass}`}>
        {/* 评论头部信息 */}
        <div className="flex items-center mb-3">
          <Avatar
            src={item.author.avatar}
            size="small"
            className="mr-3"
          >
            {item.author.username.charAt(0)}
          </Avatar>
          <div className="flex-1">
            <div className="flex items-center">
              <span className="font-medium text-gray-900">{item.author.username}</span>
              {isReply && item.replyTo && (
                <>
                  <span className="mx-2 text-gray-400">回复</span>
                  <span className="font-medium text-blue-600">@{item.replyTo.username}</span>
                </>
              )}
            </div>
            <div className="text-xs text-gray-500">
              {new Date(item.createTime).toLocaleString()}
            </div>
          </div>
        </div>

        {/* 评论内容 */}
        <div className="text-gray-800 mb-3 leading-relaxed">
          {item.content}
        </div>

        {/* 评论操作按钮 */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <Button
              type="text"
              icon={<LikeOutlined />}
              onClick={() => handleLike(item.id)}
              className="flex items-center"
            >
              <span className="ml-1">{item.likes}</span>
            </Button>
            <Button
              type="text"
              onClick={() => setReplyTo(replyTo === item.id ? null : item.id)}
              className="text-blue-600 hover:text-blue-800"
            >
              {replyTo === item.id ? '取消回复' : '回复'}
            </Button>
          </div>
        </div>

        {/* 回复输入框 */}
        {replyTo === item.id && (
          <>
            <Input.TextArea
              value={replyContent}
              onChange={(e) => setReplyContent(e.target.value)}
              placeholder={`回复 @${item.author.username}...`}
              autoSize={{ minRows: 2, maxRows: 6 }}
              className="mb-3"
            />
            <div className="flex justify-end gap-2 mt-2">
              <Button
                onClick={() => setReplyTo(null)}
                className="text-gray-600"
              >
                取消
              </Button>
              <Button
                type="primary"
                onClick={() => handleReply(item.id, item.author)}
              >
                回复
              </Button>
            </div>
          </>
        )}

        {/* 回复列表 - 所有回复都作为同一级显示 */}
        {item.replies && item.replies.length > 0 && (
          <div className="mt-4 space-y-3">
            {item.replies.map((reply) => (
              <div key={reply.id}>
                {renderCommentItem(reply, 1)}
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="mt-8">
      {contextHolder}
      <Divider>评论区</Divider>
      {/* 发表评论区域 */}
      <div className="flex items-start mb-4">
        <div className="flex-1">
          <Input.TextArea
            value={commentValue}
            onChange={(e) => setCommentValue(e.target.value)}
            placeholder="写下你的评论..."
            autoSize={{ minRows: 3, maxRows: 6 }}
            className="mb-3"
          />
          <div className="flex justify-end mt-2">
            <Button
              type="primary"
              onClick={handleComment}
            >
              发表评论
            </Button>
          </div>
        </div>
      </div>

      {/* 评论列表 */}
      <div className="space-y-4">
        {commentList.map((comment) => (
          <div key={comment.id}>
            {renderCommentItem(comment)}
          </div>
        ))}
      </div>

      <div className="mt-8 text-center text-gray-500">
        <Divider>这是所有评论，没有更多了🤐</Divider>
      </div>
    </div>
  )
});
